import javax.swing.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class Client  implements Runnable {
    private final int PORT = 12345;

    private JTextArea textArea;
    private JTextField hostField;//用来交互的
    private JTextField nameField;
    private JFrame frame;

    private boolean submit = false; //提交

    public synchronized void doSubmit() {
        this.submit = true;
        notifyAll();
    }

    public Client(JTextArea textArea, JTextField hostField,JTextField nameField,JFrame frame) {
        this.textArea = textArea;
        this.hostField = hostField;
        this.nameField = nameField;
        this.frame = frame;
    }

    private void closeConnectionWindow() {
        frame.setVisible(false);
        // 关闭连接窗口
        // 或者如果是JDialog: connectionDialog.setVisible(false);
    }

    private void openGameWindow()  {
        new GomokuGame();
    }




    @Override
    public void run() {
        try (Socket socket = new Socket(hostField.getText(), PORT);
             BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));  //封装
             PrintWriter out = new PrintWriter(socket.getOutputStream(), true)) {
            while (!Thread.currentThread().isInterrupted()) {
                synchronized (this) {   //互斥访问"他自己";值要被利用到需要（用synchronized同步这个）
                    while (!submit) {
                        try {
                            wait();   //如果没有true一直的等待
                        } catch (InterruptedException e) {
                            textArea.append(nameField.getText() + "被中断\n");
                            submit = false; //用break不合适，还会继续执行外面的循环
                            in.close();
                            out.close();
                            socket.close();
                            return;
                        }
                    }
                }
                out.println( nameField.getText());
//                String str = textField.getText();
                hostField.setText("");
//                out.println(str);
                String reply = in.readLine();   //服务器回传的信息
                textArea.append("游戏回显：" + reply + "\n");    //文本区域
                submit = false;
            }
        } catch (IOException e) {
            textArea.append("连接游戏出错：" + e.getMessage() + "\n");
        }

        textArea.append(nameField.getText() + "连接结束\n");
    }
}
